package com.shf.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.shf.domain.ResponseResult;
import com.shf.enums.AppHttpCodeEnum;
import com.shf.enums.SystemException;
import com.shf.service.UploadService;
import com.shf.util.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author 叶枫
 * @date 2023/11/10.
 */

@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public ResponseResult upload(MultipartFile img) {
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();

        //判断文件类型
        if(!originalFilename.endsWith(".png") && !originalFilename.endsWith("jpg")){
            //FILE_TYPE_ERROR代表文件类型错误的提示
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);

        }

        //如果满足判断条件，则上传文件到七牛云OSS
        //调用工具类 生成 上传文件的名字
        String filePath = PathUtils.generateFilePath(originalFilename);

        String url = upOOS(img,filePath);
        return ResponseResult.okResult(url);

    }


    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.secretKey}")
    private String secretKey;
    @Value("${oss.bucket}")
    private String  bucket;

    private String upOOS(MultipartFile imgFile,String filePath){

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "-P4MfrBLWPsuYVw2flnnJxMDknh-W7y7rAE8BepS";
//        String secretKey = "tg1UBfOfMbyh__TSUUSjDXvc65otlOm4oHiRtVrB";
//        String bucket = "yefeng-blog";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);

            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://sc8k8d95d.hd-bkt.clouddn.com/" + key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            //ignore
        }

        return "上传失败";

    }






}
